package com.dimpt.cloud.config;

import com.dimpt.cloud.common.config.ResponseInfo;
import com.dimpt.cloud.common.exception.FailedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static jdk.nashorn.internal.objects.NativeError.printStackTrace;

/**
 * IPRAN全局异常捕捉类
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务的异常处理
     *
     * 控制器的其他函数只负责关注正常的业务逻辑，所以异常逻辑由本函数完成
     *
     * @param e
     * @return
     */
    @ExceptionHandler(FailedException.class)
    public ResponseEntity<?> Failed(FailedException e){
        Map error = new HashMap();
        error.put("code",e.getCode());
        error.put("message",e.getMessgae());
        error.put("data",new ArrayList<>());
        return new ResponseEntity<Map>(error, HttpStatus.BAD_REQUEST);
    }

    /**
     * 输入参数格式错误异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> MethodArgumentNotValid(MethodArgumentNotValidException e){
        Map error = new HashMap();
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> errorList = bindingResult.getAllErrors();
        List<String> mesList=new ArrayList<String>();
        for (int i = 0; i < errorList.size(); i++) {
            mesList.add(errorList.get(i).getDefaultMessage());
        }
        error.put("code", ResponseInfo.PARAM_ERROR.getErrorCode());
        error.put("message", ResponseInfo.PARAM_ERROR.getErrorMsg());
        error.put("data",mesList);
        return new ResponseEntity<Map>(error, HttpStatus.BAD_REQUEST);
    }

    /**
     * 缺省异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> Failed(Exception e){
        System.out.printf("未知异常：" + e.getMessage());
        Map error = new HashMap();
        error.put("code", ResponseInfo.UNKNOW_ERROR.getErrorCode());
        error.put("message", ResponseInfo.UNKNOW_ERROR.getErrorMsg()+e.getMessage());
        error.put("data",new ArrayList<>());
        return new ResponseEntity<Map>(error, HttpStatus.BAD_REQUEST);
    }
}